import React, { useEffect, useState } from 'react';
import './App.css';

function print(msg, color){
  console.log(`%c${msg}`, `color: ${color}`);
}

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = { logPrefix: 'React.Component' };
  }
  componentWillMount(){ // v17 以后将会移出这个生命周期
    print(`${this.state.logPrefix} componentWillMount`, "red");
  }
  componentDidMount(){
    print(`${this.state.logPrefix} componentDidMount`, "red");
  }
  componentWillUnmount(){
    print(`${this.state.logPrefix} componentWillUnmount`, "red");
  }
  render() {
    print(`${this.state.logPrefix} render`, "red");
    return (<div>React.Component 组件</div>);
  }
}

function UserView(){
  const logPrefix = 'Function Hook';
  const [FirstMount, setFirstMount] = useState(true);
  if(FirstMount){
    print(`${logPrefix} componentWillMount`, "green");
  }
  useEffect(() => {
    setFirstMount(false);
    print(`${logPrefix} componentDidMount`, "green");
    return () => {
      setFirstMount(true);
      print(`${logPrefix} componentWillUnmount`, "green");
    };
  }, []); // 第二个参数 [] 则表示整个组件的挂在和卸载
  print(`${logPrefix} render`, "green");
  return (<div>Function Hook 组件</div>);
}

function App() {
  const [mountState, SetMountState] = useState(false);
  const addComponent = () => {
    console.log('添加组件');
    SetMountState(true);
  };
  const removeComponent = () => {
    console.log('移除组件');
    SetMountState(false);
  };
  console.log('##### App render ######');
  return (
    <div className="App">
      <button onClick={addComponent}>添加组件</button>
      <button onClick={removeComponent}>移出组件</button>
      <br />
      {mountState ? <UserView /> : ''}
      {mountState ? <Welcome /> : ''}
    </div>
  );
}

export default App;
